"""
异步执行测试计划
"""
import logging
from celery.task import PeriodicTask
from django.core import serializers
import json, time
logger = logging.getLogger('log')

# 导入所需的models
from ..models import ptTestRequestTestCase, ptTestRequest,ptResponseContentReport,ptTestHeards
from ..utilService import exeTestCase

class ptTask():
    def waitForPlan(self, id):
        """
        执行测试计划进行更改状态至---等待执行
        :param id:
        :return:
        """
        try:
            logger.info("----task 等待执行----")
            ptResponseContentReport.objects.filter(plan_id=id).update(execution_state=2, updata_time=time.strftime(
                "%Y-%m-%d %H:%M:%S", time.localtime()))
            print('wait task run')
        except Exception as e:
            logger.error(e)

    def testBeingPlan(self, id):
        """
        更换执行状态----执行中
        :param id:
        :return:
        """
        try:
            logger.info("----task 执行中----")
            ptResponseContentReport.objects.filter(plan_id=id).update(execution_state=3, updata_time=time.strftime(
                "%Y-%m-%d %H:%M:%S", time.localtime()))
        except Exception as e:
            logger.error(e)

    def testOverPlan(self, id):
        """
        更换执行状态----执行结束
        :param id:
        :return:
        """
        try:
            logger.info("----task 执行结束----")
            ptResponseContentReport.objects.filter(plan_id=id).update(execution_state=4, updata_time=time.strftime(
                "%Y-%m-%d %H:%M:%S", time.localtime()))
        except Exception as e:
            logger.error(e)

    def errorTestPlan(self, id):
        """
        执行错误
        :param id:
        :return:
        """
        try:
            logger.info("----task 执行异常，修改为错误状态---")
            ptResponseContentReport.objects.filter(plan_id=id).update(execution_state=5, updata_time=time.strftime(
                "%Y-%m-%d %H:%M:%S", time.localtime()))
        except Exception as e:
            logger.error(e)

    def testExecutePlanAsynchronously(self, id):
        """
        执行测试计划
        :param id:
        :return:
        """
        try:
            logger.info("----task 执行计划----")
            Result = ptResponseContentReport.objects.get(plan_id=id).store_test_case
            exeTestCase.exeTestCase().singleeExecutionMore(caseList=eval(Result), id=id)
        except EOFError as e:
            logger.error(e)

    def testSandEmail(self, id):
        """
        测试完成后发送邮件
        :return:
        """
        data = {}
        Result = ptResponseContentReport.objects.get(plan_id=id)
        if str(Result.execution_state) == "5":
            data["executionState"] = "失败，请联系管理员"
        else:
            data["executionState"] = "成功"
        data["plan_name"] = Result.plan_name
        store_test_case = eval(Result.store_test_case)
        data["successs_case"] = Result.successs_case
        data["fail_case"] = Result.fail_case
        data["skip_case"] = Result.skip_case
        data["case_total"] = Result.case_total
        Recombination = ''
        for i in range(len(store_test_case)):
            Rtion = ""
            caseId = store_test_case[i]
            TCResult = ptTestRequestTestCase.objects.get(case_id=caseId)
            case_name = TCResult.case_name  # 用例名字
            request_code = TCResult.request_code  # 结果
            case_request_id = TCResult.case_request_id
            TRList = ptTestRequest.objects.get(request_id=case_request_id)
            request_address = TRList.request_address  # 接口地址
            if request_code == "success":
                Rtion = "<tr><td>" + str(caseId) + "</td><td>" + str(case_name) + "</td><td>" + str(
                    request_address) + "</td><td style='color:#4CAE4C'>" + '成功' + "</td></tr>"
            else:
                Rtion = "<tr><td>" + str(caseId) + "</td><td>" + str(case_name) + "</td><td>" + str(
                    request_address) + "</td><td style='color:red'>" + '失败' + "</td></tr>"
            Recombination = Recombination + Rtion
        data["Recombination"] = Recombination
        return data

    def start(self, plan_id):
        """
        启动任务
        """

        from django_celery_beat.models import CrontabSchedule, PeriodicTask
        time = ptResponseContentReport.objects.filter(plan_id=plan_id).get()
        scheduleList = eval(time.timing_task)
        print('timing列表内容',scheduleList)
        periodic_task_name = time.plan_name
        # IntervalSchedule.DAYS = 0
        # IntervalSchedule.HOURS = 0
        # IntervalSchedule.MINUTES = 1
        # IntervalSchedule.SECONDS = 5
        # IntervalSchedule.MICROSECONDS = 0

        # schedule, created = IntervalSchedule.objects.get_or_create(every=1, period=IntervalSchedule.MINUTES, )
        schedule, _ = CrontabSchedule.objects.get_or_create(# 创建定时策略
            minute=scheduleList[0],
            hour=scheduleList[1],
            day_of_week=scheduleList[2],
            day_of_month=scheduleList[3],
            month_of_year=scheduleList[4],
            timezone='Asia/Shanghai',
        )
        periodic_task = PeriodicTask.objects.create(
            crontab=schedule,
            name=periodic_task_name,
            task='appServerCode.tasks.ExecuteTestPlanAsynchronously',
            args=json.dumps([plan_id]),
            # expires=datetime.utcnow() + timedelta(seconds=30)任务 到期
        )
        periodic_task.enabled = True
        schedule.save()
        periodic_task.save()

    def stop(self, plan_id):
        """
        停止任务
        """
        try:
            from django_celery_beat.models import CrontabSchedule, PeriodicTask
            import json, datetime
            time = ptResponseContentReport.objects.filter(plan_id=plan_id).get()
            periodic_task = PeriodicTask.objects.filter(name=time.plan_name).get()
            periodic_task.enabled = False
            periodic_task.save()
        except EOFError as e:
            logger.error(e)

    def delete(self, plan_id):
        """
        删除任务
        :param plan_id:
        :return:
        """
        try:
            self.stop(plan_id)
            from django_celery_beat.models import CrontabSchedule, PeriodicTask
            time = ptResponseContentReport.objects.filter(plan_id=plan_id).get()
            periodic_task = PeriodicTask.objects.filter(name=time.plan_name).get()
            CrontabSchedule.objects.filter(id=periodic_task.crontab_id).delete()
            PeriodicTask.objects.filter(id=periodic_task.id).delete()
        except EOFError as e:
            logger.error(e)

    def starPublicInter(self):
        """
        开始update公共部分接口
        :return:
        """
        try:
            logger.info("--------跑异步任务更新headers---------------")
            mmhth = ptTestHeards.objects.all()
            logger.info("--------see ptTestHeards.objects.all() ---------------")
            data = json.loads(serializers.serialize("json", mmhth))
            if data == [] or data == "":
                logger.info("没有可执行的头部信息")
            else:
                for i in range(len(data)):
                    exeTestCase.exeTestCase().runRepositoryPublicMethod(id=int(data[i]['fields']['tpi_id']))
                logger.info('---头部信息更新完成---')
        except EOFError as e:
            logger.error(e)